package com.fluidops.datacatalog.reltables;

import java.util.Set;
import java.util.TreeSet;

import com.fluidops.datacatalog.reltables.model.Dataset;
import com.fluidops.datacatalog.reltables.model.Entity;
import com.fluidops.datacatalog.reltables.schemascore.ConsistencyScore;
import com.fluidops.datacatalog.reltables.schemascore.ISchemaScore;

public class SchemaComplementScorer {

	private ISchemaScore schemaScore;
	
	public SchemaComplementScorer(ISchemaScore schemaScore){
		this.schemaScore = schemaScore;
	}
	
	public double compareDatasets(Dataset d1, Dataset d2){

		double coverage = entityCoverage(d1, d2);
		double benefit = benefit(d1, d2);
		
		double similarity = coverage * benefit;
		//add to related dataset list
		d1.addRelatedDataset(d2, similarity);
		
		return similarity;
	}
	
	
	private double benefit(Dataset d1, Dataset d2){
		double benefit = 0d;
		
		Set<String> dimensions1 = d1.dimValueStringLabels();
		Set<String> dimensions2 = d2.dimValueStringLabels();
		
		benefit = this.schemaScore.compareSchemas(dimensions1, dimensions2);
		
		return benefit;
	}
	
	private double entityCoverage(Dataset d1, Dataset d2){
		double coverage = 0d;
		
		Set<Entity> entities1 = d1.getEntities(); 
		Set<Entity> entities2 = d2.getEntities(); 
		
		Set<String> ds1Labels = new TreeSet<String>();
		for(Entity e : entities1){
			ds1Labels.addAll(e.getLabels());
		}
		int numEntity1Labels = ds1Labels.size();
	
		Set<String> ds2Labels = new TreeSet<String>();
		for(Entity e : entities2){
			ds2Labels.addAll(e.getLabels());
		}

		int commonLabels = 0;
		for(String label : ds1Labels){
			if(ds2Labels.contains(label)){
				commonLabels++;
			}
		}
		
		if(numEntity1Labels > 0){
			coverage = (double)commonLabels / (double)numEntity1Labels;
		}
		
		return coverage;
	}
	
	public ConsistencyScore getConsistencyScore(){
		return this.schemaScore.getConsistencyScore();
	}
	
}
